package edu.sjtu.erplab.cm.dao.impl;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class BaseHibernateDAO extends HibernateDaoSupport {
	private static final Logger log = LoggerFactory
			.getLogger(BaseHibernateDAO.class);

	@Resource(name = "sessionFactory")
	public void setSuperSessionFactory(SessionFactory sessionFactory) {
		super.setSessionFactory(sessionFactory);
	}

	public List findByHql(String hql) {
		log.debug("findByHql: " + hql);
		try {
			return getHibernateTemplate().find(hql);
		} catch (RuntimeException re) {
			log.error("findByHql:" + hql, re);
			throw re;
		}
	}

	public boolean executeUpdateSql(String sql) {
		Connection conn = null;
		Statement stmt = null;
		Session session = getSession();
		try {
			conn = session.connection();
			stmt = conn.createStatement();
			int rs = stmt.executeUpdate(sql);
			return rs > 0 ? true : false;
		} catch (Exception e) {

			e.printStackTrace();
			return false;
		} finally {
			if (stmt != null) {
				try {
					stmt.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}

	}

	public Object saveOrUpdate(Object o) {

		try {
			getHibernateTemplate().saveOrUpdate(o);
			return o;
		} catch (RuntimeException re) {
			log.error("saveOrUpdate:", re);
			throw re;
		}
	}
}
